//
//  SaoMiaoController.m
//  药品通_石小强
//
//  Created by shixiaoqiang on 16/1/12.
//  Copyright © 2016年 shixiaoqiang. All rights reserved.
//

#import "SaoMiaoController.h"
#import <AVFoundation/AVFoundation.h>
#import "MBProgressHUD.h"
#import "SaoMiaoResultController.h"
#import "UIView+Frame.h"
#define SHColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0f]
static const CGFloat kBorderW = 120;
static const CGFloat kMargin = 30;

@interface SaoMiaoController ()<AVCaptureMetadataOutputObjectsDelegate, UIAlertViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) UIView *maskView;
@property (nonatomic, strong) UIView *scanWindow;
@property (nonatomic, strong) UIImageView *scanNetImageView;
@property (nonatomic, strong) UIView *selectView;
@property (nonatomic, weak) UITextField *selectText;
@property (nonatomic, assign) CGFloat keyboardHeight;
@property (nonatomic, weak) UIButton *flashBtn;

@end

@implementation SaoMiaoController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 1.隐藏tabbar
//    self.navigationController.navigationBar.hidden = NO;
//    self.automaticallyAdjustsScrollViewInsets = NO;
//
//    // 2.设置导航栏
//    [self createNavigationBar];
    // 3.打开属性，防止返回的时候出现黑边
    self.view.clipsToBounds = YES;
    
    // 4.遮罩
    [self setupMaskView];
    
    // 5.下边栏
    [self setupBottomBar];
    
    // 6.提示文本
    [self setupTipTitleView];
    
    // 7.查询视图
    [self createSelectView];
    
    // 8.扫描区域
    [self setupScanWindowView];
    
    // 9.开始动画
    [self beginScanning];
    
    [self setNavBar];
    // 10.设置通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(resumeAnimation) name:@"EnterForeground" object:nil];
}



/**
 *  开始动画
 */
- (void)beginScanning
{
    //获取摄像设备
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //创建输入流
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    if (!input) return;
    //创建输出流
    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
    //设置代理 在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    //设置有效扫描区域
    CGRect scanCrop=[self getScanCrop:_scanWindow.bounds readerViewBounds:self.view.frame];
    
    [output setRectOfInterest:scanCrop];
    
    //初始化链接对象
    _session = [[AVCaptureSession alloc]init];
    //高质量采集率
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    [_session addInput:input];
    [_session addOutput:output];
    //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    
    AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
    layer.frame=self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
    //开始捕获
    [_session startRunning];
}

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count>0) {
        [_session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"扫描结果" message:metadataObject.stringValue delegate:self cancelButtonTitle:@"退出" otherButtonTitles:@"再次扫描", nil];
        [alert show];
    }
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self disMiss];
    } else if (buttonIndex == 1) {
        [_session startRunning];
    }
}

#pragma mark-> 返回
- (void)disMiss
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark-> 获取扫描区域的比例关系
-(CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds
{
    
    CGFloat x,y,width,height;
    
    x = (CGRectGetHeight(readerViewBounds)-CGRectGetHeight(rect))/2/CGRectGetHeight(readerViewBounds);
    y = (CGRectGetWidth(readerViewBounds)-CGRectGetWidth(rect))/2/CGRectGetWidth(readerViewBounds);
    width = CGRectGetHeight(rect)/CGRectGetHeight(readerViewBounds);
    height = CGRectGetWidth(rect)/CGRectGetWidth(readerViewBounds);
    
    return CGRectMake(x, y, width, height);
    
}

/**
 *  扫描区域
 */
- (void)setupScanWindowView
{
    CGFloat scanWindowH = self.view.width - kMargin * 6;
    CGFloat scanWindowW = self.view.width - kMargin * 6;
    _scanWindow = [[UIView alloc] initWithFrame:CGRectMake(kMargin * 3, kBorderW, scanWindowW, scanWindowH)];
    _scanWindow.clipsToBounds = YES;
    [self.view addSubview:_scanWindow];
    
    _scanNetImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"scan_net"]];
    CGFloat buttonWH = 18;
    
    UIButton *topLeft = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, buttonWH, buttonWH)];
    [topLeft setImage:[UIImage imageNamed:@"scan_1"] forState:UIControlStateNormal];
    [_scanWindow addSubview:topLeft];
    
    UIButton *topRight = [[UIButton alloc] initWithFrame:CGRectMake(scanWindowW - buttonWH, 0, buttonWH, buttonWH)];
    [topRight setImage:[UIImage imageNamed:@"scan_2"] forState:UIControlStateNormal];
    [_scanWindow addSubview:topRight];
    
    UIButton *bottomLeft = [[UIButton alloc] initWithFrame:CGRectMake(0, scanWindowH - buttonWH, buttonWH, buttonWH)];
    [bottomLeft setImage:[UIImage imageNamed:@"scan_3"] forState:UIControlStateNormal];
    [_scanWindow addSubview:bottomLeft];
    
    UIButton *bottomRight = [[UIButton alloc] initWithFrame:CGRectMake(topRight.x, bottomLeft.y, buttonWH, buttonWH)];
    [bottomRight setImage:[UIImage imageNamed:@"scan_4"] forState:UIControlStateNormal];
    [_scanWindow addSubview:bottomRight];
}

/**
 *  提示文本
 */
-(void)setupTipTitleView{
    UILabel * tipLabel = [[UILabel alloc] init];
//    tipLabel.frame = CGRectMake(10, 20 + 64, WIDTH - 20, 50);
    tipLabel.frame = CGRectMake(10, 64, WIDTH - 20, 50);
    tipLabel.text = @"请将条码置于取景器内扫描，距离大约10cm，尽量避免反光。开启闪光灯等有助于弱光条件下识别。";
    tipLabel.textColor = [UIColor whiteColor];
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.lineBreakMode = NSLineBreakByWordWrapping;
    tipLabel.numberOfLines = 2;
    tipLabel.font=[UIFont systemFontOfSize:12];
    tipLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tipLabel];
}

/**
 *  下边栏
 */
- (void)setupBottomBar
{
    //1.下边栏
//    UIView *bottomBar = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height - 49, self.view.width, 49)];
    UIView *bottomBar = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height - 49 , self.view.width, 49)];
    bottomBar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomBar];
    
    // 2.手动输入按钮
    UIButton *editBtn = [[UIButton alloc] init];
    editBtn.frame = CGRectMake(10, 8, 32, 32);
    [editBtn setBackgroundImage:[UIImage imageNamed:@"scan_edit_code"] forState:UIControlStateNormal];
    [editBtn addTarget:self action:@selector(editBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [bottomBar addSubview:editBtn];
    
    // 3.闪光灯按钮
    UIButton *flashBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    flashBtn.frame = CGRectMake(WIDTH - 42, 8, 32, 32);
    [flashBtn setBackgroundImage:[UIImage imageNamed:@"scan_close_flash_lamp"] forState:UIControlStateNormal];
    [flashBtn setBackgroundImage:[UIImage imageNamed:@"scan_open_flash_lamp"] forState:UIControlStateSelected];
    [flashBtn addTarget:self action:@selector(flashBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.flashBtn = flashBtn;
    [bottomBar addSubview:flashBtn];
}

/**
 *  弹出查询视图
 */
- (void)editBtnClick {
    [self.selectText becomeFirstResponder];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.selectView.y = self.view.height - self.keyboardHeight - 50;
    } completion:^(BOOL finished) {
        
    }];
}

/**
 *  隐藏查询视图
 */
- (void)hideSelectView {
    
    [UIView animateWithDuration:0.5 animations:^{
        self.selectView.y = self.view.height;
        [self.selectText resignFirstResponder];
    } completion:^(BOOL finished) {
        
    }];
    
}

/**
 *  跳转页面
 */
- (void)selectBtnClick {
    [UIView animateWithDuration:0.5 animations:^{
        self.selectView.y = self.view.height;
        [self.selectText resignFirstResponder];
    } completion:^(BOOL finished) {
        
    }];
    if (self.selectText.text.length == 0) {
        // 请输入条码数字
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"请输入条码数字";
        hud.margin = 10.0f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        return;
    }
    
    SaoMiaoResultController *controller = [[SaoMiaoResultController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}

/**
 *  创建查询视图
 */
- (void)createSelectView {
    UIView *selectView = [[UIView alloc] init];
    selectView.backgroundColor = [UIColor blackColor];
    selectView.frame = CGRectMake(0, self.view.height, WIDTH, 50);
    UITextField *selectText = [[UITextField alloc] init];
    selectText.backgroundColor = SHColor(174, 174, 174);
    selectText.placeholder = @"手动输入条码数字";
    selectText.frame = CGRectMake(10, 5, WIDTH - 90, 40);
    selectText.layer.borderWidth = 1.0;
    selectText.layer.cornerRadius = 20.0;
    selectText.keyboardType = UIKeyboardTypeNumberPad;
    self.selectText = selectText;
    [selectView addSubview:selectText];
    
    UIButton *selectBtn = [[UIButton alloc] init];
    selectBtn.frame = CGRectMake(WIDTH - 70, 5, 60, 40);
    [selectBtn setTitle:@"查询" forState:UIControlStateNormal];
    [selectBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [selectBtn setBackgroundColor:[UIColor blueColor]];
    selectBtn.layer.borderWidth = 1.0;
    selectBtn.layer.cornerRadius = 20.0;
    [selectBtn addTarget:self action:@selector(selectBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [selectView addSubview:selectBtn];
    
    self.selectView = selectView;
    [self.view addSubview:selectView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}

- (void)keyBoardWillShow:(NSNotification *)sender {
    NSDictionary * dict = sender.userInfo;
    CGRect rect =  [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardHeight = rect.size.height;
    self.keyboardHeight = keyboardHeight;
}

/*
 UIKeyboardAnimationCurveUserInfoKey = 7;
 UIKeyboardAnimationDurationUserInfoKey = "0.25";
 UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {414, 226}}";
 UIKeyboardCenterBeginUserInfoKey = "NSPoint: {207, 849}";
 UIKeyboardCenterEndUserInfoKey = "NSPoint: {207, 623}";
 UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 736}, {414, 226}}";
 UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 510}, {414, 226}}";
 UIKeyboardIsLocalUserInfoKey = 1;
 */

/**
 *  开关闪光灯
 */
- (void)flashBtnClick {
    self.flashBtn.selected = !self.flashBtn.selected;
    if (self.flashBtn.selected) {
        [self turnTorchOn:YES];
    }
    else{
        [self turnTorchOn:NO];
    }
}

#pragma mark-> 开关闪光灯
- (void)turnTorchOn:(BOOL)on {
    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
        if ([device hasTorch] && [device hasFlash]){
            [device lockForConfiguration:nil];
            if (on) {
                [device setTorchMode:AVCaptureTorchModeOn];
                [device setFlashMode:AVCaptureFlashModeOn];
                
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
                [device setFlashMode:AVCaptureFlashModeOff];
            }
            [device unlockForConfiguration];
        }
    }
}

#pragma mark-> 我的二维码
-(void)myCode{
//    NSLog(@"我的二维码");
}

/**
 *  遮罩
 */
- (void)setupMaskView
{
    CGFloat scanWindowH = self.view.width - kMargin * 6;
    CGFloat scanWindowW = self.view.width - kMargin * 6;
    
    UIView *viewTop = [[UIView alloc] init];
    viewTop.frame = CGRectMake(0, 0, WIDTH, kBorderW);
    viewTop.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
    viewTop.userInteractionEnabled = YES;
    [self.view addSubview:viewTop];
    // 添加手势管理
    UITapGestureRecognizer *tgrTop = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideSelectView)];
    [viewTop addGestureRecognizer:tgrTop];
    
    UIView *viewLeft = [[UIView alloc] init];
    viewLeft.frame = CGRectMake(0, kBorderW, kMargin * 3, scanWindowH);
    viewLeft.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
    viewLeft.userInteractionEnabled = YES;
    [self.view addSubview:viewLeft];
    // 添加手势管理
    UITapGestureRecognizer *tgrLeft = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideSelectView)];
    [viewLeft addGestureRecognizer:tgrLeft];
    
    UIView *viewRight = [[UIView alloc] init];
    viewRight.frame = CGRectMake(kMargin * 3 + scanWindowW, kBorderW, kMargin * 3, scanWindowH);
    viewRight.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
    viewRight.userInteractionEnabled = YES;
    [self.view addSubview:viewRight];
    // 添加手势管理
    UITapGestureRecognizer *tgrRight = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideSelectView)];
    [viewRight addGestureRecognizer:tgrRight];
    
    UIView *viewBottom = [[UIView alloc] init];
    viewBottom.frame = CGRectMake(0, kBorderW + scanWindowH, WIDTH, self.view.height - kBorderW - scanWindowH - 49);
    viewBottom.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
    viewBottom.userInteractionEnabled = YES;
    [self.view addSubview:viewBottom];
    // 添加手势管理
    UITapGestureRecognizer *tgrBottom = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideSelectView)];
    [viewBottom addGestureRecognizer:tgrBottom];
}

/**
 *  设置导航栏
 */

-(void)setNavBar
{
    MyNavigationItem * leftItem = [MyNavigationItem navigationItemWithImage:@"ic_bg_white_arrow_left" andHighlightImage:@"ic_bg_white_arrow_left" andTag:0 andTitle:nil addTarget:self action:@selector(leftBtnClick)];
    
    MyNavigationBar * navBar = [[MyNavigationBar alloc]initWithFrame:CGRectMake(0, 20, self.view.width, 44)];
    navBar.backgroundColor = [UIColor whiteColor];
    
    UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(0, navBar.frame.size.height-0.5, navBar.frame.size.width, 0.5)];
    lineView.backgroundColor =[UIColor grayColor];
    [navBar addSubview:lineView];
    
    [navBar setNavigationBarWithBgImageName:@"无" andTitle:@"条码扫描"  andTitleView:nil andLeftItems:@[leftItem] andRightItems:nil];
    [self.view addSubview:navBar];

}
/**
 *  导航栏返回按钮点击事件
 */
- (void)leftBtnClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self resumeAnimation];
    self.navigationController.navigationBar.hidden = NO;

}

#pragma mark 恢复动画
- (void)resumeAnimation
{
    CAAnimation *anim = [_scanNetImageView.layer animationForKey:@"translationAnimation"];
    if(anim){
        // 1. 将动画的时间偏移量作为暂停时的时间点
        CFTimeInterval pauseTime = _scanNetImageView.layer.timeOffset;
        // 2. 根据媒体时间计算出准确的启动动画时间，对之前暂停动画的时间进行修正
        CFTimeInterval beginTime = CACurrentMediaTime() - pauseTime;
        
        // 3. 要把偏移时间清零
        [_scanNetImageView.layer setTimeOffset:0.0];
        // 4. 设置图层的开始动画时间
        [_scanNetImageView.layer setBeginTime:beginTime];
        
        [_scanNetImageView.layer setSpeed:3.0];
        
    }
    else
    {
        CGFloat scanNetImageViewH = 241;
        CGFloat scanWindowH = self.view.width - kMargin * 2;
        CGFloat scanNetImageViewW = _scanWindow.width;
        
        _scanNetImageView.frame = CGRectMake(0, -scanNetImageViewH, scanNetImageViewW, scanNetImageViewH);
        CABasicAnimation *scanNetAnimation = [CABasicAnimation animation];
        scanNetAnimation.keyPath = @"transform.translation.y";
        scanNetAnimation.byValue = @(scanWindowH);
        scanNetAnimation.duration = 3.0;
        scanNetAnimation.repeatCount = MAXFLOAT;
        [_scanNetImageView.layer addAnimation:scanNetAnimation forKey:@"translationAnimation"];
        [_scanWindow addSubview:_scanNetImageView];
    }
}

@end
